package com.han.demo.repository;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hanjl
 * @Description jpa通用查询
 * @ClassName CommonRepository
 * @createTime 2021/11/15 14:26
 */
@Repository
@Transactional(propagation= Propagation.NOT_SUPPORTED,rollbackFor = Exception.class)
@Slf4j
public class CommonRepository {

    @Resource
    private EntityManagerFactory entityManagerFactory;

    public List<Map<String,Object>> commonQuery(String sql, Map<String,Object> params){
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            Query query = entityManager.createNativeQuery(sql);
            setQueryParameter(sql,params,query);
            //这个作用是让query.getResultList()返回值转换为List<Map<String,Object>>，不加转换报错
            query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            List<Map<String,Object>> list = query.getResultList();
            if (CollectionUtils.isEmpty(list)){
                return new ArrayList();
            }
            //转换成大写
            List<Map<String, Object>> finalResult = new ArrayList<>();
            list.forEach(map -> {
                Map<String, Object> finalMap = new HashMap<>();
                map.forEach((k,v) -> finalMap.put(k.toUpperCase(), v));
                finalResult.add(finalMap);
            });
            return finalResult;

        } catch (Exception e){
            log.error("查询失败",e);
            throw e;
        } finally {
            closeEntityManager(entityManager);
        }
    }

    private String setPageSql(String sql, int offset, int size){
        if (true){
            return "select * from (select temp_table.*,rownum rn from (" + sql +" )temp_table where rownum <="+(offset+size)+") where rn > "+offset;
        }else {
            return sql + " limit " + offset + " , " + size;
        }
    }

    /**
     * jpa设置查询参数
     * @param sql
     * @param params
     * @param query
     */
    private void setQueryParameter(String sql ,Map<String,Object> params,Query query){
        if(params != null && !params.isEmpty()){
            for(String key : params.keySet()){
                if(sql.contains(":" + key)){
                    query.setParameter(key,params.get(key));
                }
            }
        }
    }

    /**
     * 关闭
     * @param entityManager
     */
    public void closeEntityManager(EntityManager entityManager){
        entityManager.close();
    }

}
